import pyautogui as pg
import os
import time
import pyperclip
import requests
import json
import psutil
import sys
import win32gui, win32com.client
import win32api
import win32con
import win32process  
import ctypes
from pywinauto.application import Application

def check_qdy_qdg(file_name):
    file_name_split = file_name.split('.')
    file_ext = file_name_split[-1].lower()
    file_pre = file_name_split[0].lower()
    return file_pre, file_ext


def open_file(file_path):
    hwnd = win32gui.FindWindow(None, "广联达云计价平台GCCP6.0")
    print(hwnd)
    app = Application(backend='uia').connect(handle=hwnd)
    dlg = app.window(title=win32gui.GetWindowText(hwnd))  # 根据你的窗口标题进行调整  
    file_list = dlg.child_window(title="最近文件", control_type="Button")
    file_list.click()
    print(dlg.print_ctrl_ids())
    dlg['最近文件ListItem0'].double_click_input()




def start_export():
    hwnd = win32gui.FindWindow(None, "广联达云计价平台GCCP6.0")



# 关闭软件
def close_software():
    time.sleep(10)
    pids = psutil.pids()
    for pid in pids:
        p = psutil.Process(pid)
        process_name = p.name()
        if process_name.startswith('QDJJ'):
            # 杀掉指定进程
            # print('kill process: name: %s - pid: %s' %(process_name, pid))
            find_kill = 'taskkill -f -pid %s' % pid
            os.popen(find_kill)

# 导出成功
def export_success(id, file_name):
    url = '''http://127.0.0.1:9135/rpa/runSuccess'''
    data = {
        "id" : id,
        "file_name" : file_name
    }
    headers = {
        'Content-Type': 'application/json'
    }
    requests.post(url = url, data = json.dumps(data), headers= headers)


# 异常处理
def export_failed(id, errorMsg):
    url = '''http://127.0.0.1:9135/rpa/runFailed'''
    data = {
        "id" : id,
        "errMsg": errorMsg
    }
    headers = {
        'Content-Type': 'application/json'
    }
    requests.post(url = url, data = json.dumps(data), headers=headers)

def delete_files_in_directory(directory):  
    for filename in os.listdir(directory):  
        file_path = os.path.join(directory, filename)  
        try:  
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)  
            elif os.path.isdir(file_path): 
                delete_files_in_directory(file_path)
                os.rmdir(file_path)
            # 这里不处理目录，所以不需要elif os.path.isdir(file_path):  
        except Exception as e:  
            print(f'Failed to delete {file_path}. Reason: {e}') 

pg.FAILSAFE = False 

# 程序被唤起 参数为文件本地地址 文件id
# dir_path = sys.argv[1]
# need_export_file_name = sys.argv[2]
# id = int(sys.argv[3])


# 获取盘符
# drive_letter = dir_path[0]



# 获取

try :
    open_file("123")
    # close_software()
    # time.sleep(5)
    # 检测到导出成功窗口后5秒关闭软件
except Exception as e:
    # close_software()
    # export_failed(id, str(e))
    time.sleep(5)